/***************************
 * control.js
 * The UI Controller
 * Author: PKM
 ****************************/
var uiManager = new UIManager(); 
var game = new Game();

var STATE_INIT			= 0;
var STATE_LOADING		= 1;
var STATE_WAITING 		= 2;
var STATE_FUNCTION		= 3;	//Phase 3 or Phase 5
var STATE_MESSAGE		= 4;	//Phase 4.0
var STATE_TRANSMIT		= 5;	//Phase 4.1
var STATE_TRANSMIT_M	= 51;
var STATE_TRANSMIT_O	= 52;
var STATE_ARRIVED		= 6;	//Phase 4.2
var STATE_CONFIRM		= 7;	//Phase 4.3  < doing
var STATE_BLOCK			= 8;	//phase 7 NOT IMPLEMENT
var STATE_SUBMIT        = 9;	//NOT USED
//var STATE_CONFIRM		= 8;

var STATE_TABLE = new Array();
STATE_TABLE[3] = STATE_FUNCTION;
STATE_TABLE[5] = STATE_FUNCTION;
STATE_TABLE[40] = STATE_MESSAGE;
STATE_TABLE[41] = STATE_TRANSMIT;
STATE_TABLE[42] = STATE_ARRIVED;
STATE_TABLE[43] = STATE_CONFIRM;
STATE_TABLE[7] = STATE_BLOCK;

var STATE_TIMEOUT = new Array();
STATE_TIMEOUT[STATE_FUNCTION] = 5000;
STATE_TIMEOUT[STATE_MESSAGE] = 5000;
STATE_TIMEOUT[STATE_TRANSMIT] = 5000;
STATE_TIMEOUT[STATE_ARRIVED] = 5000;
STATE_TIMEOUT[STATE_CONFIRM] = 5000;
STATE_TIMEOUT[STATE_BLOCK] = 5000;


function helper_get_state(){
	var state = STATE_TABLE[game.phase];
	if(!state) state = STATE_TABLE[game.phase*10 +game.state];
	if(!state) state = STATE_WAITING;
	return state;
}
function helper_get_timeout(){
	return STATE_TIMEOUT[helper_get_state()];
}

var STATE_FUNCTIONS		= new Array();

var LAST_STATE			= -1;
var STATE				= -1;

var TURNS = -1;

var UPDATE_INTERVAL = 1000;

var debug= false;

function control_init(){
	if(STATE_FUNCTIONS.length == 0){
		STATE_FUNCTIONS[STATE_LOADING] = doLoading;
		STATE_FUNCTIONS[STATE_INIT] 	= doInit;
		STATE_FUNCTIONS[STATE_WAITING] = doWaiting;
		STATE_FUNCTIONS[STATE_FUNCTION] = doPlayFunction;
		STATE_FUNCTIONS[STATE_MESSAGE] = doPlayMessage;
		STATE_FUNCTIONS[STATE_TRANSMIT] = doPlayTransmit;
		STATE_FUNCTIONS[STATE_ARRIVED] = doPlayArrived;
		STATE_FUNCTIONS[STATE_CONFIRM] = doConfirm;
		STATE_FUNCTIONS[STATE_BLOCK]    = doPlayBlock;
	}
	setState(STATE_INIT);
}

function setState(state){
	if(STATE != state){
	//if(true){
		console.log("State Change :" + state);
		LAST_STATE = STATE;
		STATE  = state;
		if(STATE_FUNCTIONS[STATE] != null){
			STATE_FUNCTIONS[STATE]();
		}		
	}
}
/////////////////////////////


//////////////////////////////////////////////////////////
//
//Put the server data into local
//

function loadInput(data){
	for (var i = 0; i < data.player.length; i++) {
		var player;
		
		
		if (game.players[i] == null) {
			player = new Player(data.player[i][0], data.player[i][1], data.player[i][4], "img/" + data.player[i][5]);
			game.addPlayer(player);
		}else{
			player = game.players[i];
			player.clearMessageCard();
			player.clearFunctionCard();
		}
		
		var card = data.player[i][2];
		for (var j = 0; j < card.length; j++) {
			player.addMessageCard(getCard(card[j]));
		}
		
		var card = data.player[i][3];
		for (var j = 0; j < card.length; j++) {
			player.addFunctionCard(getCard(card[j]));
		}
	}
}

function updateGameState(states){

	game.phase = states[0];
	game.state = states[1];
	game.round = states[2];
	game.turn = states[3];
	
	
	uiManager.stopAllPlayerTimer();
	
	uiManager.update(game);
	uiManager.selfUI.unselectFunctionCard();	
	uiManager.unselectCharacter();
	uiManager.unselectBlackCard();
		
	if(game.turn == game.uid){ 
		setState(helper_get_state());
	}else{
		uiManager.playerArray[game.turn - 1 % game.total_player].timer.start(helper_get_timeout());
		//start other players timer
		
		setState(STATE_WAITING);
	}
	
	showStatus();	
}


//////////////////////////////////////////////////////////
//
//Load the game setting from server
//

//init the UI
function doInit(){		
	console.log("Init...");
	
	$('.loading').toggle(true);
	$('.main').toggle(false);
	
	uiManager.init();
	game.init();
	

	setState(STATE_LOADING);
}

function doLoading(){	
	console.log("Loading...");
	if (!debug) {
		$.getJSON("interface.php?action=init", {
			pid: UID
		}, onLoaded);
	}else{
		onLoaded();
	}
	
}


//onloaded the game setting from server
function onLoaded(data){
	
	game.myid = UID-1;
	game.uid = UID;
	game.state = 0;
	game.turn = 0;	
			
	if (!debug) {
		loadInput(data);
	}
	else {
		for (var i = 0; i < 9; i++) {
			var player = new Player(i,i % 3 + 1,i+"", "img/" + i + ".gif");
			game.addPlayer(player);
		}
	}
		
	uiManager.createAllPlayer(game);
	
	$('.loading').toggle(false);
	$('.main').toggle(true);
	
	setInterval(keepUpdate,UPDATE_INTERVAL);
	setState(STATE_WAITING);
}



function doWaiting(){
	console.log("Waiting");
}



function doPlayMessage(){	
	
	var targets = game.getPlayerIds();
	var cards = game.players[game.myid].getCardWithFunction(game.card[STATE_MESSAGE]);
	var card = null;
	var target = 0;
	var onCharacterSelected = function(pid){
		target = game.players[pid].id;
		uiManager.unselectCharacter();
		send(card.id,target);
	}
	var onCardSelected = function(c){
		card = c;
		if (card.tid == 3) {
			uiManager.selectCharacter(targets, onCharacterSelected);
		}
		else {
			send(card.id, target);
		}
	}	
	var autoPlayMessage = function(){
		
		if(card == null){
			card = getCard(cards[get_random(cards.length)]);
		}
		if(card.tid == 3){
			pid =  targets[get_random(targets.length)];
			target = game.players[pid].id;
		}
		send(card.id,target);
	}
	
	var send = function(cid,target){
		uiManager.selfUI.timer.stop();
		uiManager.selfUI.unselectFunctionCard();
		uiManager.unselectCharacter();
		sendPlay(cid,target,2);
		//setState(STATE_WAITING);
	}
	
	if (game.round == game.uid) {	
		uiManager.selfUI.selectFunctionCard(cards, onCardSelected);
		uiManager.selfUI.timer.start(helper_get_timeout(), autoPlayMessage);
	}else{		
		send(game.current_message_info[0],game.current_message_info[3]);
	}
	
}

function doPlayFunction(){
	console.log("Play Function")
	var cards = game.card[STATE_FUNCTION];	
	doFunction(cards);
}

function doPlayArrived(){
	console.log("Play Arrived");	
	var cards = game.card[STATE_ARRIVED];
	doFunction(cards);
}

function doConfirm(){
	
	var send = function(accept){
		var target = game.current_message_info[0]		
		uiManager.selfUI.timer.stop();
		uiManager.unselectCurrentMessage();
		sendPlay(target,accept,3);
	}
	
	var onCardSelected = function(){
		send(1);
	}
	
	var timeoutCallback = function(){
		send(0);		
	}
	
	uiManager.selectCurrentMessage(onCardSelected);
	uiManager.selfUI.timer.start(helper_get_timeout(),timeoutCallback);	
}

function doPlayBlock(){	
	var cards = game.card[STATE_BLOCK];
	doFunction(cards);	
}

function doPlayTransmit(){
	var cards = (game.round == game.uid) ?
			game.card[STATE_TRANSMIT_M]:
			game.card[STATE_TRANSMIT_O];
	doFunction(cards);
}

function doFunction(card_functions){	
	var cards = game.players[game.myid].getCardWithFunction(card_functions);
	
	var send = function(cid,target){		
		uiManager.selfUI.timer.stop();
		uiManager.selfUI.unselectFunctionCard();
		sendPlay(cid,target,1);
	}
	
	var onFunctionCardSelected = function(c){
		var targets;
		var card = c;
		var target = 0;
		var onCharacterSelected = function(pid){
			target = game.players[pid].id;
			uiManager.unselectCharacter();
			send(card.id,target);
		}
		
		var onBlackCardSelected = function(c){
			uiManager.unselectBlackCard();
			send(card.id, c.id)			
		}
		
		switch(card.fid){
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
				send(card.id,target);
			break;
			case 8:
				uiManager.selectBlackCard(onBlackCardSelected);
			break;	
			case 1:	
				targets=game.getPlayerIdsWithoutLock();
				uiManager.selectCharacter(targets, onCharacterSelected);
			break;
			case 7:	
			case 9:		
				targets=game.getPlayerIds();
				uiManager.selectCharacter(targets, onCharacterSelected);
			break;	
		}
	}
	
	var timeoutCallback = function(){
		uiManager.selfUI.unselectFunctionCard();
		uiManager.unselectCharacter();
		uiManager.unselectBlackCard();
		send(0,0);
	}

	uiManager.selfUI.selectFunctionCard(cards,onFunctionCardSelected);
	uiManager.selfUI.timer.start(helper_get_timeout(),timeoutCallback);
}	


function sendPlay(card,target,type){
	showHistory("PID:" + game.uid + ",cid:" + card + ",target:" + target + ",type"+type);
	$.getJSON("interface.php?action=play",{
		pid:game.uid,
		cid:card,
		target:target,
		type:type
	},onReceived);
}

function keepUpdate(){
	$.getJSON("interface.php?action=update",
	{pid:game.uid},onReceived);	
}
/*
function onUpdateReceived(data){
	loadInput(data);
}*/

var last_message = "";
function onReceived(data){	

	var state = data.game_states;
	//nothing changed
	if(
		game.phase == state[0]&&
		game.state == state[1]&&
		game.round == state[2]&&
		game.turn == state[3]
	) return;
	
	game.current_message_info = data.message;
	
	
	
	////////////////////////
	if( helper_get_state() == STATE_TRANSMIT ||
		helper_get_state() == STATE_ARRIVED	||
		helper_get_state() == STATE_CONFIRM){	
		uiManager.displayDeskMessage(data.message);		
	}else{
		uiManager.hideDeskMessage();		
	}
	
	//show log
	if (data.display_message != last_message) {
		last_message = data.display_message;
		showHistory(data.display_message);
	}
	
	if (STATE == STATE_WAITING) {
		loadInput(data);
	}
	
	updateGameState(state);		
	//setState(STATE_WAITING);
}

function showStatus(msg){
	if(!msg){
		msg = "Player:" + game.uid + "State[" + game.phase + "," + game.state + "," + game.round + "," + game.turn +"]";
	}
	uiManager.showStatus(msg);
}

function showHistory(msg){
	uiManager.showHistory(msg);	
}

$(document).ready(function(){
	control_init();
})
